package com.kingbook.api.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.kingbook.core.annotations.ContainProperties;
import com.kingbook.core.auth.LoginManager;
import com.kingbook.core.result.JSONResult;
import com.kingbook.entity.Master;
import com.kingbook.entity.Partner;
import com.kingbook.services.MasterService;
import com.kingbook.services.PartnerService;
import com.kingbook.services.WorkorderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

import static com.kingbook.core.auth.LoginManager.AUTH;

/**
 * @Author Bucky
 * @Date 2020-01-08 21:13:15
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("partner")
public class PartnerRest {

    @Autowired
    PartnerService partnerService;

    @Autowired
    MasterService masterService;

    @Autowired
    WorkorderService workorderService;

    @PutMapping
    @ContainProperties({"id", "name", "relatedMid"})
    public JSONResult save(@RequestBody Map<String, Object> param, @RequestHeader(name = AUTH) String auth) {
        param.put("mid", LoginManager.getMid(auth));
        log.info("---->{}", param);
        return partnerService.updatePartner(param);
    }

    @DeleteMapping("{id}")
    public JSONResult remove(@PathVariable int id, @RequestHeader(name = AUTH) String auth) {
        int mid = LoginManager.getMid(auth);
        log.info("---->mid={} id={}", mid, id);
        Map<String, Object> param = Maps.newHashMap();
        param.put("mid", mid);
        param.put("id", id);
        JSONResult result = partnerService.query(param);
        if (result.isSuccess() && result.getCount() > 0) {
            JSONObject json = result.getData().getJSONObject(0);
            int count = json.getIntValue("workspaceCount") + json.getIntValue("orderCount") + json.getIntValue("allotOrderCount") + json.getIntValue("allotToOrderCount");
            if (count == 0) {
                Map<String, Object> params = Maps.newHashMap();
                params.put("mid", json.getString("relatedMid"));
                params.put("myRelatedMid", mid);
                params.put("referralCode", 0);
                params.put("relatedMid", 0);
                partnerService.modify(params);
                return partnerService.remove(id, mid);
            }
            return JSONResult.failed("该合作伙伴已经添加了你的工单，不能删除！");
        }
        return JSONResult.failed("该合作伙伴不存在！");
    }

    @GetMapping("{id}")
    public JSONResult find(@PathVariable int id, @RequestHeader(name = AUTH) String auth) {
        int mid = LoginManager.getMid(auth);
        log.info("---->mid={} id={}", mid, id);
        return partnerService.find(id, mid);
    }

    @PostMapping("query")
    public JSONResult query(@RequestBody Map<String, Object> param, @RequestHeader(name = AUTH) String auth) {
        param.put("mid", LoginManager.getMid(auth));
        log.info("---->{}", param);
        JSONResult result = partnerService.query(param);
        JSONArray array = result.getData();
        JSONArray newArray = new JSONArray();
        for (int i = 0; i < array.size(); i++) {
            JSONObject order = array.getJSONObject(i);
            JSONObject json = new JSONObject();
            json.put("id", order.getIntValue("id"));
            int relatedMid = order.getIntValue("relatedMid");
            int referralCode = order.getIntValue("referralCode");
            int shortNumber = order.getIntValue("shortNumber");
            json.put("avatarUrl", order.getString("avatarUrl"));
            json.put("title", order.getString("name"));
            json.put("subTitle", "推荐码 " + (referralCode > 0 ? referralCode : ""));
            json.put("lable", relatedMid > 0 ? "已认证" : "查找好友");
            json.put("lableTap", relatedMid == 0);
            json.put("desc1", "短号: " + (shortNumber > 0 ? shortNumber : ""));
            json.put("desc2", "手机: " + order.getString("phone1") + " " + order.getString("phone2") + " " + order.getString("phone3"));
            json.put("desc3", "公司: " + order.getString("company"));
            json.put("desc4", "地址: " + order.getString("address"));
            json.put("desc5", "备注: " + order.getString("remarks"));
            int workspaceCount = order.getIntValue("workspaceCount");
            int orderCount = order.getIntValue("orderCount") + order.getIntValue("allotOrderCount");
            int allotToOrderCount = order.getIntValue("allotToOrderCount");
            json.put("workspaceCount", workspaceCount);
            json.put("orderCount", orderCount);
            json.put("del", workspaceCount == 0 && orderCount == 0 && allotToOrderCount == 0);
            newArray.add(json);
        }
        result.setData(newArray);
        return result;
    }

    @PostMapping("pages")
    @ContainProperties({"pageNo", "pageSize"})
    public JSONResult queryForPages(@RequestBody Map<String, Object> param, @RequestHeader(name = AUTH) String auth) {
        param.put("mid", LoginManager.getMid(auth));
        log.info("---->{}", param);
        return partnerService.queryForPages(param);
    }

}
